const {
  serviceId, bindPassword, cubeSendUuidNotify,
  cubeReceiveUuidWrite, parseRes, writeBLECharacteristicValue,
  reply, connect, parseAdvertisData, setNameOfCube, bluetoothAdapterState, discovery, closeCube,specialData
} = require('../../utils/bluetooth');
const {
  ab2hex, alert, array2arrayBuffer, digit2hex,
  getSeqNum, isIOS, log, timeFormat,matchedDevicesHandler,
  string2utf8array, utf8arrayFixedLength,lengthCount,
  query2obj, jump, getCubeName, json2string, getInfoByDeviceId, currentPageName, getCubeInfoJson, setCubeInfo, cubeIsOnline
} = require('../../utils/util');
const {Event} = require('../../utils/constant');
let deviceId, serialNumber, needConnect, cubeName, isShare = false, connectTimerId;
// let onShare = false;
const app = getApp();

Page({
  data: {
    editing:false,
    isFocus:false,

    cubeName: '',
    timeDesc: '',
    pm25: '--',
    hcho: '--',
    battery: 0,
    isCharging: 0,
    productId: '',
    matchStatus: 4,// 4 离线， 3 在线
  },
  jumpDevices: function () {
    if (getCurrentPages().length > 1) {
      wx.navigateBack();
    } else {
      jump({pageName: 'devices', type: 1});
    }
  },

  defaultData: function () {
    return {
      // cubeName: '',
      timeDesc: '',
      pm25: '--',
      hcho: '--',
      battery: 0,
      isCharging: 0,
      // productId: '',
      matchStatus: 4,// 4 离线， 3 在线
    }
  },
  inputDone:function(event){

    const that = this;
    this.setData({
      editing:false,
      isFocus:false
    });

    let {value} = event.detail;
    value = value.trim();
    const {cubeName} = this.data;
    if(!value){
      // wx.showToast({title:''});
      return;
    }else if(cubeName===value){
      return;
    }else if(lengthCount(value)>15){
      wx.showToast({title:'字符数需不大于15',icon:'none'});
      return;
    }else{
      this.setData({cubeName:value});
      setCubeInfo({serialNumber,info:{cubeName:value}});
      matchedDevicesHandler({serialNumber,cubeName:value,action:'modify'});
    }


  },
  bindEditInput:function(){

  },
  editName:function(){
    const that = this;
    this.setData({
      editing:true
    });
    //晃动
    setTimeout(function () {
      that.setData({
        isFocus:true
      })
    },200);
  },
  onLoad: function (option) {

    const that = this;

    this.connectIsFail = this.connectIsFail.bind(this); //主动去连接的回调
    this.connectInvoke = this.connectInvoke.bind(this);
    this.offline = this.offline.bind(this);


    // const {share} = option;
    // isShare = share - 0 === 1;
    // if (isShare) {
    //   serialNumber = option.serialNumber;
    //   cubeName = option.cubeName;
    //   needConnect = cubeIsOnline(serialNumber) ? 0 : 1;
    // }

    app.event.on(Event.BluetoothAdapterStateChange, that.BluetoothAdapterStateChangeHandler, that);
    app.event.on(Event.BLEConnectionStateChange, that.BLEConnectionStateChangeHandler, that);
    // app.event.on(Event.BLECharacteristicValueChange, that.BLECharacteristicValueChangeHandler, that);
    app.event.on(Event.BLEDiscoveryWhenOffline, that.BLEDiscoveryWhenOfflineHandler, that);
    // app.event.on(Event.AppInForground, that.AppInForgroundHandler, that);
    app.event.on(Event.DataTransfer, that.DataTransferHandler, that);
  },

  onUnload: function () {
    //redirect时触发，navigate不触发
    //转发或小程序进入后台时，ios不触发
    const that = this;
    app.event.off(Event.BluetoothAdapterStateChange, this.BluetoothAdapterStateChangeHandler);
    app.event.off(Event.BLEConnectionStateChange, this.BLEConnectionStateChangeHandler);
    // app.event.off(Event.BLECharacteristicValueChange, this.BLECharacteristicValueChangeHandler);
    app.event.off(Event.BLEDiscoveryWhenOffline, this.BLEDiscoveryWhenOfflineHandler);
    // app.event.off(Event.AppInForground, this.AppInForgroundHandler);
    app.event.off(Event.DataTransfer, this.DataTransferHandler);

  },

  onShow: function () {

    // return;

    const that = this;

    this.setData({
      editing:false,
      isFocus:false
    });

    serialNumber = wx.getStorageSync('lastCubeSerialNumber') + '';
    //cubeName = wx.getStorageSync('lastCubeName') || '';
    needConnect = wx.getStorageSync('needConnect');

    // if (!isShare) {
    //   serialNumber = wx.getStorageSync('lastCubeSerialNumber') + '';
    //   //cubeName = wx.getStorageSync('lastCubeName') || '';
    //   needConnect = wx.getStorageSync('needConnect');
    // } else {
    //   isShare = false; //解决场景：点击分享卡片后，无法切换cube（只能访问分享的cube）
    // }

    if (serialNumber) {

      this.setData({productId: serialNumber.substring(6, 10)});

      const info = getCubeInfoJson(serialNumber + '');


      console.log(`deviceInfo onShow时，cube ${info.matchStatus-0===4?'离线':'在线'}`);

      if (info) {
        this.setData(info);
      } else {
        this.setData(this.defaultData());
      }

      const cubeIsDisconnecting = wx.getStorageSync('cubeIsDisconnecting');//&& cubeIsDisconnecting-0!==1
      if (needConnect - 0 === 1 && !cubeIsOnline()) {

        that.connectInvoke();
      } else {
      }

    }

    // onShare = false;
  },
  DataTransferHandler:function({id,info}){
    if(id+'' === serialNumber+''){
      this.setData(info);
      //setCubeInfo({serialNumber, info});//不可在这设置，考虑页面不存在的场景
    }
  },
  // AppInForgroundHandler:function(){
  //   this.connectInvoke();
  // },
  BLEDiscoveryWhenOfflineHandler: function () {
    this.connectInvoke();
  },
  offline: function () {
    const data = {matchStatus: 4, isCharging: 0};
    this.setData(data);
    setCubeInfo({serialNumber, info: data});
  },
  BluetoothAdapterStateChangeHandler: function (available) {
    if (available) {
      this.connectInvoke();
    } else {
      this.offline();
    }
  },
  BLEConnectionStateChangeHandler: function ({connected, deviceId}) {
    //根据deviceId找到serialNumber

    if (connected) {

    } else {
      try{
        const {serialNumber:id} = getInfoByDeviceId(deviceId);
        log(json2string(getInfoByDeviceId(deviceId)));
        if(id+'' === serialNumber+''){
          this.setData({matchStatus: 4, isCharging: 0});
        }
      }catch (e) {

      }


    }

  },
  onReady: function () {

  },
  notSupportHCHO:function () {
    /*
      7000 pm2.5
    * 7001 pm2.5 甲醛
    * */
    const productId = serialNumber.substring(6, 10);
    return productId-0 !== 7001;
  },
  statusDesc:function (type,value,status) {
    /*
    type:0 pm2.5，1 甲醛
    * */
    var desc = [['优','良','污染'],['优','良','污染']],index;
    if(0===type) {
      index = value<=35?0:value<=75?1:2;
    }else if(1===type){
      index = value<=0.08?0:value<=0.10?1:2;
    }
    if('--'===value){
      index = 0;
    }
    return '--'===value?'':desc[type][index];
  },
  onShareAppMessage: function (options) {
    //app.globalData.ignoreAppOnHide = true;
    // onShare = true;
    const { pm25, hcho } = this.data;

    // console.log(`${pm25} ${hcho}`);

    const notHCHO = this.notSupportHCHO();

    // console.log(`${notHCHO}`)

    let title = '';

    title += `PM2.5   ${pm25}μg/m³   ${this.statusDesc(0,pm25)}`;
    if(!notHCHO){
      title+=`\r\n甲醛  ${hcho}mg/m³   ${this.statusDesc(1,hcho)}`;
    }

    // console.log(title)

    return {
      title,
      path: `/pages/searchBySerialNumber/searchBySerialNumber?id=${serialNumber}`, //用户点击卡片，看到的页面
      imageUrl:'./images/sharingPicture.png',//卡片的内容
      success: function (res) {
        // alert(res);
      },
      fail: function (res) {
        // alert(res);
      },
      complete: function () {

      }
    }
  },
  onHide: function () {
    //navigate时触发，redirect不触发

  },
  connectIsFail: function () {
    this.setData({matchStatus: 4, isCharging:0});
    setCubeInfo({serialNumber, info: {matchStatus: 4,isCharging:0}});
  },

  connectInvoke: function () {

    console.log('connectInvoke 开始');

    const that = this;

    let isFound = false;

    discovery(function (devices) {
      try {
        const dv = devices.devices[0];
        const {localName, name, deviceId: deviceIdAlias, advertisData} = dv; //deviceId是mac地址，cube重启后可能会变
        const {serialNumber: serialNumberFound} = parseAdvertisData(advertisData);

        if (serialNumberFound + '' === serialNumber + '' && !isFound) {
          deviceId = deviceIdAlias;
          isFound = true;
          // const cubeName = getCubeName({serialNumber});
          that.setData({cubeName:getCubeName({serialNumber})});
          wx.stopBluetoothDevicesDiscovery({
            complete: function () {
              //stopBluetoothDevicesDiscovery成功后，再调用connect，非常重要。
              console.log(`has found. willConnect: serialNumber=${serialNumber},deviceId=${deviceId}`);
              connect({
                  deviceId,
                  connectSuccess: function () {
                    console.log(`serialNumber:${serialNumber},deviceId:${deviceId} 连接成功`);
                    // setCubeInfo({serialNumber, info: {deviceId, cubeName,matchStatus: 3}});
                    setCubeInfo({serialNumber, info: {deviceId, cubeName:getCubeName({serialNumber})}});
                  },
                  fail: that.connectIsFail,
                  complete: function () {
                    // 如果在后台，断开连接
                    if(!app.globalData.appInForground){
                      console.log('!!!app.globalData.appInForground closeCube');
                      closeCube();
                      //wx.setStorageSync('needConnect',1);
                    }else{
                      wx.setStorageSync('autoReconnect', 1);
                      console.log('deviceInfo页，连接完成时，成功设置autoReconnect为1');
                    }
                  }
                },
              );
            }
          });
        }
      } catch (e) {
      }
    }, function () {
    })


  },

  onPullDownRefresh: function () {
    const that = this;

    try {

      writeBLECharacteristicValue({
        deviceId,
        value: [getSeqNum(), 0x31],
        success: res => {
          log('主动请求Sensor Real Time Data成功');
        }, fail: function (res) {
          log('主动请求Sensor Real Time Data错误');
          that.connectInvoke();
        },
        complete: function () {

        }
      });
    } catch (e) {

    }

    setTimeout(wx.stopPullDownRefresh, 2500);

  },
  jumpWebView: function () {
    // jump({pageName:'webView',params:{url:'http://app-smarthome.siemens.com.cn/appdownload-guide.html'},type:1});
    // jump({pageName:'webView',params:{url:'https://itunes.apple.com/cn/app/id478868966?mt=8'},type:1});
    jump({
      pageName: 'webView',
      params: {url: 'https://server-dev.developmentservice.cn/appdownload-guide.html'},
      type: 1
    });
    // jump({pageName:'webView',params:{url:'https://mc.zhuyaping.com'},type:1});
    return;
    wx.setClipboardData({
      data: 'https://a.app.qq.com/o/simple.jsp?pkgname=com.ipconnect',
      success: function () {
        wx.showToast({
          title: '下载链接已复制，请在浏览器中粘贴访问',
          icon: 'none',
          duration: 4000
        })
      },
      fail: function () {
        wx.showToast({
          title: '功能不可用',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }
});
